import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Button,
  Row,
  Col,
  Space,
  Form,
  Checkbox,
  Tabs,
  Modal,
  Select,
  DatePicker,
  Input,
  Radio,
  InputNumber,
  Dropdown,
  message,
  Tooltip,
  Menu,
  notification,
} from 'antd';
import {
  PlusOutlined,
  QuestionCircleOutlined,
  RightOutlined,
  DownOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import BomTree from './bomTree';
import { connect } from 'umi';
import moment from 'moment';
import * as Request from '@/services/Request';
import { ResourceGrpSelect, ResourceSelect, OpMasterSelect } from '@/components/FormItemSelect';
import PartSelect from '@/components/PartSelect';

const { TabPane } = Tabs;
const { confirm } = Modal;
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
const apiURL = '/api/services/app/PartBOM/';
const apiURLBoo = '/api/services/app/PartBOO/';
const apiURLMtl = '/api/services/app/PartMtl/';
class ViewPage extends React.Component<any, any> {
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      dataSource: [],
      defTab: '1',
      defTab2: 'S1',
      currPartBom: null,
      currPartBoo: {},
      currPartMtl: {},
      rootPart: {
        partNum: '',
        bomLevel: 0,
      },
      BomData: {},
    };
  }
  formRef: any = React.createRef();
  bomTree: any = BomTree;
  onFinish = (values: any) => {
    var PartRoot = values.PartBOM;
    var PartBOM = values.Asmbl;
    var PartBOO = values.PartBOO;
    var PartMtl = values.PartMtl;
    const { defTab, defTab2 } = this.state;
    if (defTab == '1') {
      this.savePartBom(PartRoot);
    } else {
      if (defTab2 == 'S1') {
        this.savePartBoo(PartBOO);
      } else if (defTab2 == 'S2') {
        this.savePartBom(PartBOM);
      } else {
        this.savePartMtl(PartMtl);
      }
    }
  };
  savePartBom = (PartBOM: any) => {
    const { rootPart } = this.state;
    PartBOM.effectiveDate = PartBOM.effectiveDate?.format('YYYY-MM-DD');
    PartBOM.approved = !PartBOM.approved ? false : PartBOM.approved;
    PartBOM.inActive = !PartBOM.inActive ? false : PartBOM.inActive;
    PartBOM.parentPartNum = rootPart.partNum != PartBOM.partNum ? rootPart.partNum : '';
    PartBOM.parentRevision = rootPart.revisionNum;
    PartBOM.bomLevel = rootPart.bomLevel + 1;
    PartBOM.bomType = rootPart.bomType;
    var act = 'Create';
    var method = 'POST';
    if (PartBOM.id) {
      act = 'Update';
      method = 'PUT';
    }
    Request.post(apiURL + act, PartBOM, method).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
          this.getBom();
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        this.setState({ loading: false });
      }
    });
  };
  savePartBoo = (PartBOO: any) => {
    const { currPartBom } = this.state;
    if (currPartBom) {
      PartBOO.partNum = currPartBom.partNum;
      PartBOO.revisionNum = currPartBom.revisionNum;
    }
    var act = 'Create';
    var method = 'POST';
    if (PartBOO.id) {
      act = 'Update';
      method = 'PUT';
    }
    Request.post(apiURLBoo + act, PartBOO, method).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
          this.getBom();
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        this.setState({ loading: false });
      }
    });
  };
  savePartMtl = (PartMtl: any) => {
    const { currPartBom } = this.state;
    if (currPartBom) {
      PartMtl.bOMPartNum = currPartBom.partNum;
      PartMtl.bOMPartRev = currPartBom.revisionNum;
    }
    var act = 'Create';
    var method = 'POST';
    if (PartMtl.id) {
      act = 'Update';
      method = 'PUT';
    }
    PartMtl.mfgComment = '-';
    PartMtl.purComment = '-';
    PartMtl.relatedOpRev = 'A';

    Request.post(apiURLMtl + act, PartMtl, method).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
          this.getBom();
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        this.setState({ loading: false });
      }
    });
  };
  setCurrent = (part?: any) => {
    var PartBOM: any = {};
    PartBOM.partNum = part.partNum;
    PartBOM.partDescription = part.partDescription;
    PartBOM.ium = part.ium;
    this.formRef.current.setFieldsValue({ PartBOM });
    this.setState({ partRevs: part.revs });
  };
  setCurrent2 = (part?: any) => {
    var Asmbl: any = {};
    Asmbl.partNum = part.partNum;
    Asmbl.partDescription = part.partDescription;
    Asmbl.ium = part.ium;
    this.formRef.current.setFieldsValue({ Asmbl });
    this.setState({ currPartBom: Asmbl, partRevs2: part.revs });
  };
  setCurrent3 = (part?: any) => {
    var PartMtl: any = {};
    PartMtl.partNum = part.partNum;
    PartMtl.partDescription = part.partDescription;
    PartMtl.ium = part.ium;
    this.formRef.current.setFieldsValue({ PartMtl });
  };
  setCurrentAsmb = (item: any, type: string) => {
    console.log(item);

    if (type == 'mtl') {
      this.setState({ currPartMtl: item, defTab: '2', defTab2: 'S3' });
      this.formRef.current.setFieldsValue({ PartMtl: item });
    } else if (type == 'asm') {
      this.setState({ currPartBom: item, defTab: '2', defTab2: 'S2' });
      this.formRef.current.setFieldsValue({ Asmbl: item });
    } else if (type == 'boo') {
      this.setState({ currPartBoo: item, defTab: '2', defTab2: 'S1' });
      this.formRef.current.setFieldsValue({ PartBOO: item });
    } else {
      this.setState({ currPartBom: item, defTab: '1', rootPart: item });
      this.formRef.current.setFieldsValue({ PartBOM: item });
    }
  };
  getBom = () => {
    var obj = this.formRef.current.getFieldsValue();
    var PartNum = obj.PartBOM.partNum;
    var RevNum = obj.PartBOM.revisionNum;
    if (PartNum && RevNum) {
      Request.get(apiURL + 'GetBOM?partNum=' + PartNum + '&revNum=' + RevNum).then(
        (response: any) => {
          var BomData = response?.result;
          if (BomData && BomData.node) {
            this.setState({ BomData });
            this.bomTree.fetchData(response.result);
            BomData.node.effectiveDate = moment(BomData.node?.effectiveDate);
            if (BomData.childs && BomData.childs.length > 0) {
              this.setCurrentAsmb(BomData.childs[0].node, 'asm');
            }
            if (BomData.boos && BomData.boos.length > 0) {
              this.setCurrentAsmb(BomData.boos[0].node, 'boo');
              var mtls = BomData.boos[0].mtls;
              if (mtls && mtls.length > 0) {
                this.setCurrentAsmb(mtls[0], 'mtl');
              }
            }
            this.setCurrentAsmb(BomData.node, 'root');
          }
        },
      );
    }
  };
  tabSwitch = (key: any) => {
    this.setState({ defTab: key });
  };
  tabSwitch2 = (key: any) => {
    this.setState({ defTab2: key });
  };
  onRef = (ref: any) => {
    this.bomTree = ref;
  };
  ResetForm = () => {
    this.formRef.current.resetFields();
  };
  handleMenuClick = (e: any) => {
    if (e.key === '1') {
      this.ResetForm();
      this.setState({ defTab: '1' });
    } else if (e.key === '2') {
      this.formRef.current.setFieldsValue({ PartBOO: null });
      this.setState({ defTab: '2', defTab2: 'S1' });
    } else if (e.key === '3') {
      this.formRef.current.setFieldsValue({ Asmbl: null });
      this.setState({ defTab: '2', defTab2: 'S2' });
    } else {
      this.formRef.current.setFieldsValue({ PartMtl: null });
      this.setState({ defTab: '2', defTab2: 'S3' });
    }
  };
  cacheData = async () => {
    this.getBom();
  };
  delObj = () => {
    const { defTab, defTab2, currPartMtl, currPartBom, currPartBoo } = this.state;
    let ctrl = 'PartBom';
    let id = 0;
    if (defTab == '1') {
      ctrl = 'PartBom';
    } else {
      if (defTab2 == 'S1') {
        ctrl = 'PartBoo';
        id = currPartBoo.id;
      } else if (defTab2 == 'S2') {
        ctrl = 'PartBom';
        id = currPartBom.id;
      } else {
        ctrl = 'PartMtl';
        id = currPartMtl.id;
      }
    }
    let _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.props
          .dispatch({
            type: 'Abp/delete',
            payload: { id },
            control: ctrl,
          })
          .then(() => {
            _this.getBom();
          });
      },
    });
  };
  render() {
    const { BomData, defTab, defTab2, partRevs, partRevs2 } = this.state;
    const selectRev = (
      <Select placeholder="选择版本" onChange={this.getBom}>
        {partRevs?.map((item: any) => {
          return (
            <Select.Option key={item} value={item}>
              {item}
            </Select.Option>
          );
        })}
      </Select>
    );
    const selectRev2 = (
      <Select placeholder="选择版本">
        {partRevs2?.map((item: any) => {
          return (
            <Select.Option key={item} value={item}>
              {item}
            </Select.Option>
          );
        })}
      </Select>
    );
    return (
      <PageHeaderWrapper>
        <Form {...layout} ref={this.formRef} onFinish={this.onFinish}>
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <BomTree BomData={BomData} onRef={this.onRef} setCurrentAsmb={this.setCurrentAsmb} />
            </Col>
            <Col span={16}>
              <Card
                title={'BOM设计'}
                extra={
                  <Space>
                    <Dropdown
                      overlay={
                        <Menu onClick={this.handleMenuClick}>
                          <Menu.Item key="1" icon={<RightOutlined />}>
                            新建BOM
                          </Menu.Item>
                          <Menu.Item key="2" icon={<RightOutlined />}>
                            新建工序
                          </Menu.Item>
                          <Menu.Item key="3" icon={<RightOutlined />}>
                            新建半成品
                          </Menu.Item>
                          <Menu.Item key="4" icon={<RightOutlined />}>
                            新建物料
                          </Menu.Item>
                        </Menu>
                      }
                    >
                      <Button type="primary" icon={<PlusOutlined />}>
                        新增 <DownOutlined />
                      </Button>
                    </Dropdown>

                    <Button type="primary" htmlType="submit">
                      保存
                    </Button>
                    <Button type="dashed" onClick={this.cacheData}>
                      刷新
                    </Button>
                    <Button danger icon={<CloseOutlined />} onClick={this.delObj}>
                      删除
                    </Button>
                  </Space>
                }
              >
                <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
                  <TabPane tab="版本" key="1">
                    <Row>
                      <Col span={12}>
                        <Form.Item label="物料编码" style={{ marginBottom: 0 }}>
                          <Input.Group compact>
                            <PartSelect
                              name={['PartBOM', 'partNum']}
                              noStyle
                              width={200}
                              required={true}
                              placeholder="物料编码"
                              setCurrent={this.setCurrent}
                            />
                            <Form.Item
                              name={['PartBOM', 'revisionNum']}
                              rules={[{ required: true, message: '版本必填' }]}
                            >
                              {selectRev}
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                        <Form.Item name={['PartBOM', 'id']} hidden={true}>
                          <Input />
                        </Form.Item>
                        <Form.Item label="物料描述" name={['PartBOM', 'partDescription']}>
                          <Input disabled={true} />
                        </Form.Item>
                        <Form.Item
                          label="生效日期"
                          name={['PartBOM', 'effectiveDate']}
                          rules={[{ required: true, message: '生效日期必填' }]}
                        >
                          <DatePicker />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label="BOM类型"
                          name={['PartBOM', 'bomType']}
                          rules={[{ required: true }]}
                        >
                          <Select style={{ width: 200 }} placeholder="BOM类型">
                            <Select.Option value="des">设计</Select.Option>
                            <Select.Option value="mfg">制造</Select.Option>
                          </Select>
                        </Form.Item>
                        <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ offset: 5 }}>
                          <Input.Group compact>
                            <Form.Item name={['PartBOM', 'inActive']} valuePropName="checked">
                              <Checkbox defaultChecked={false}>无效</Checkbox>
                            </Form.Item>
                            <Form.Item name={['PartBOM', 'approved']} valuePropName="checked">
                              <Checkbox defaultChecked={false}>核准</Checkbox>
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                        <Form.Item label="数量/父项">
                          <Input.Group compact>
                            <Form.Item
                              noStyle
                              name={['PartBOM', 'qtyPer']}
                              rules={[{ required: true, message: '数量必填' }]}
                            >
                              <InputNumber min={1} />
                            </Form.Item>
                            <Form.Item
                              noStyle
                              name={['PartBOM', 'ium']}
                              rules={[{ required: true }]}
                            >
                              <Input placeholder="单位" style={{ width: 80 }} />
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                      </Col>
                    </Row>
                  </TabPane>
                  <TabPane tab="制造工艺" key="2">
                    <Tabs defaultActiveKey={defTab2} activeKey={defTab2} onChange={this.tabSwitch2}>
                      <TabPane tab="工序" key="S1">
                        <Row>
                          <Col span={12}>
                            <Form.Item name={['PartBOO', 'id']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'partNum']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'revisionNum']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'oprSeq']} label="序号">
                              <InputNumber min={1} step={1} />
                            </Form.Item>
                            <Form.Item style={{ marginBottom: 0 }} label="工序">
                              <Input.Group compact>
                                <OpMasterSelect
                                  width={200}
                                  required={true}
                                  showSearch={true}
                                  name={['PartBOO', 'opCode']}
                                />
                                <Form.Item name={['PartBOO', 'opDesc']}>
                                  <Input placeholder="工序描述" />
                                </Form.Item>
                              </Input.Group>
                            </Form.Item>
                            <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ offset: 5 }}>
                              <Input.Group compact>
                                <Form.Item
                                  name={['PartBOO', 'subContract']}
                                  valuePropName="checked"
                                >
                                  <Checkbox>外包</Checkbox>
                                </Form.Item>
                                <Form.Item name={['PartBOO', 'finalOpr']} valuePropName="checked">
                                  <Checkbox>最后工序</Checkbox>
                                </Form.Item>
                                <Form.Item
                                  name={['PartBOO', 'autoReceive']}
                                  valuePropName="checked"
                                >
                                  <Checkbox>自动收货</Checkbox>
                                </Form.Item>
                              </Input.Group>
                            </Form.Item>
                            <Form.Item
                              name={['PartBOO', 'machines']}
                              label={
                                <span>
                                  排程块数&nbsp;
                                  <Tooltip title="生产排程中可排的机器数量。例如，中心有4台机器，每天8小时，运行2台机器。此操作每天将消耗16小时的容量。因此，如果它有32个小时的预计产量，它将计划为2天。注：这只适用于生产小时数，总设置小时数将添加到压缩的生产小时数中，以获得计划的小时数。但是，它用于计算操作的总设置小时数。">
                                    <QuestionCircleOutlined />
                                  </Tooltip>
                                </span>
                              }
                            >
                              <InputNumber style={{ width: 100 }} min={0} />
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'schedRelation']} label="排程方式">
                              <Radio.Group name="radiogroup">
                                <Radio value="SS">开始-到-开始</Radio>
                                <Radio value="FS">结束-到-开始</Radio>
                                <Radio value="FF">结束-到-结束</Radio>
                              </Radio.Group>
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'setHoursPerMach']} label="小时">
                              <InputNumber style={{ width: 100 }} min={0} />
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'addlSetUpQty']} label="附加准备数量">
                              <InputNumber style={{ width: 100 }} min={0} />
                            </Form.Item>
                            <Form.Item name={['PartBOO', 'addlSetupHours']} label="附加准备时间">
                              <InputNumber style={{ width: 100 }} min={0} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item label="生产标准">
                              <Input.Group compact>
                                <Form.Item
                                  noStyle
                                  name={['PartBOO', 'prodStandard']}
                                  rules={[{ required: true, message: '请输入生产标准' }]}
                                >
                                  <InputNumber style={{ width: 200 }} min={0} />
                                </Form.Item>
                                <Form.Item noStyle name={['PartBOO', 'stdFormat']}>
                                  <Select placeholder="小时/件" style={{ width: 90 }}>
                                    <Select.Option value="HP">小时/件</Select.Option>
                                    <Select.Option value="MP">分钟/件</Select.Option>
                                    <Select.Option value="PM">件/分钟</Select.Option>
                                    <Select.Option value="OH">件/小时</Select.Option>
                                  </Select>
                                </Form.Item>
                              </Input.Group>
                            </Form.Item>
                            <ResourceGrpSelect
                              width={200}
                              required={true}
                              showSearch={true}
                              name={['PartBOO', 'resourceGrpID']}
                              label="资源群组"
                            />
                            <ResourceSelect
                              width={200}
                              required={true}
                              showSearch={true}
                              name={['PartBOO', 'resourceID']}
                              label="资源"
                            />
                            <Form.Item label="工序备注" name={['PartBOO', 'commentText']}>
                              <Input.TextArea rows={3} />
                            </Form.Item>
                          </Col>
                        </Row>
                      </TabPane>
                      <TabPane tab="半成品" key="S2">
                        <Row>
                          <Col span={12}>
                            <Form.Item name={['Asmbl', 'bomSeq']} label="序号">
                              <InputNumber min={1} step={1} />
                            </Form.Item>
                            <Form.Item label="物料编码">
                              <Input.Group compact>
                                <PartSelect
                                  name={['Asmbl', 'partNum']}
                                  noStyle
                                  width={200}
                                  required={true}
                                  placeholder="物料编码"
                                  setCurrent={this.setCurrent2}
                                  pType="M"
                                />
                                <Form.Item noStyle name={['Asmbl', 'revisionNum']}>
                                  {selectRev2}
                                </Form.Item>
                              </Input.Group>
                            </Form.Item>
                            <Form.Item name={['Asmbl', 'partDescription']} label="描述">
                              <Input disabled />
                            </Form.Item>
                            <Form.Item name={['Asmbl', 'id']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['Asmbl', 'parentPartNum']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['Asmbl', 'parentRevision']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item label="数量/父项">
                              <Input.Group compact>
                                <Form.Item
                                  noStyle
                                  name={['Asmbl', 'qtyPer']}
                                  rules={[{ required: true, message: '需求数量必填' }]}
                                >
                                  <InputNumber min={1} style={{ width: 120 }} />
                                </Form.Item>
                                <Form.Item
                                  noStyle
                                  name={['Asmbl', 'ium']}
                                  rules={[{ required: true }]}
                                >
                                  <Input disabled style={{ width: 80, marginRight: 10 }} />
                                </Form.Item>
                                <Form.Item name={['Asmbl', 'fixedQty']} valuePropName="checked">
                                  <Checkbox>固定数量</Checkbox>
                                </Form.Item>
                              </Input.Group>
                            </Form.Item>
                          </Col>
                        </Row>
                      </TabPane>
                      <TabPane tab="物料" key="S3">
                        <Row>
                          <Col span={12}>
                            <Form.Item name={['PartMtl', 'id']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['PartMtl', 'bOMPartNum']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['PartMtl', 'bOMPartRev']} hidden>
                              <Input />
                            </Form.Item>
                            <Form.Item name={['PartMtl', 'mtlSeq']} label="物料序号">
                              <InputNumber min={1} step={1} />
                            </Form.Item>
                            <Form.Item label="物料编码">
                              <Input.Group compact>
                                <PartSelect
                                  name={['PartMtl', 'partNum']}
                                  noStyle
                                  width={200}
                                  required={true}
                                  placeholder="物料编码"
                                  setCurrent={this.setCurrent3}
                                  pType="P"
                                />
                              </Input.Group>
                            </Form.Item>
                            <Form.Item name={['PartMtl', 'partDescription']} label="描述">
                              <Input disabled />
                            </Form.Item>
                            <Form.Item label="相关工序" name={['PartMtl', 'relatedOperation']}>
                              <Input placeholder="10" />
                            </Form.Item>
                            <Form.Item label="数量/父项">
                              <Input.Group compact>
                                <Form.Item
                                  noStyle
                                  name={['PartMtl', 'qtyPer']}
                                  rules={[{ required: true, message: '需求数量必填' }]}
                                >
                                  <InputNumber min={1} style={{ width: 120 }} />
                                </Form.Item>
                                <Form.Item
                                  noStyle
                                  name={['PartMtl', 'ium']}
                                  rules={[{ required: true, message: '单位必填' }]}
                                >
                                  <Input
                                    style={{ width: 70, marginRight: 10 }}
                                    disabled
                                    placeholder="单位"
                                  />
                                </Form.Item>
                                <Form.Item name={['PartMtl', 'fixedQty']} valuePropName="checked">
                                  <Checkbox>固定数量</Checkbox>
                                </Form.Item>
                              </Input.Group>
                            </Form.Item>
                          </Col>
                          <Col span={12}></Col>
                        </Row>
                      </TabPane>
                    </Tabs>
                  </TabPane>
                </Tabs>
              </Card>
            </Col>
          </Row>
        </Form>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
